const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const cors = require("koa2-cors");
const { koaBody } = require("koa-body");
const onerror = require("koa-onerror");
const logger = require("koa-logger");
const path = require("path");
const index = require("./routes/index");
const fse = require("fs-extra");
require("./utils/db");

// error handler
onerror(app);
// middlewares
app
  .use(cors())
  .use(
    views(__dirname + "/views", {
      extension: "ejs",
    })
  )
  .use(
    koaBody({
      multipart: true, //解析多个文件
      formidable: {
        maxFileSize: 100 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
        uploadDir: path.join(__dirname, `public/upload/`), // 设置文件上传目录
        keepExtensions: true,
        onFileBegin: async (name, file) => {
          if (name === "file") {
            const fileNameArr = file.originalFilename.split("||");
            let name = fileNameArr[0].split("//")[1].split("--")[0];
            const dir = path.join(__dirname, `public/file/`);
            let index = fileNameArr[0].split("--")[1];
            if (!fse.existsSync(dir)) {
              // 创建大文件的临时目录
              try {
                await fse.mkdirs(dir);
              } catch (error) {
                console.log(error);
              }
            }

            file.filepath = `${dir}/${index}`;
          }
        },
        onError: (err) => {
          console.log(err, "上传错误");
        },
      },
    })
  )
  .use(json())
  .use(logger())
  .use(require("koa-static")(__dirname + "/public"))
  .use(require("koa-static")(__dirname + "/public/upload"))
  .use(require("koa-static")(__dirname + "/views/"))
// logger


// routes
app.use(index.routes(), index.allowedMethods());

// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
